package com.example.myblog.controller;

import com.example.myblog.model.SocialLink;
import com.example.myblog.service.*;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 处理关于我页面的控制器
 */
@Controller
public class AboutController {

    @Resource
    private SettingsService settingsService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private UserService userService;

    @Resource
    private MarkdownService markdownService;

    @Resource
    private OssService ossService;

    // 设置键名常量
    private static final String ABOUT_NAME = "about_name";
    private static final String ABOUT_AVATAR = "about_avatar";
    private static final String ABOUT_BIO = "about_bio";
    private static final String ABOUT_CONTENT = "about_content";
    private static final String ABOUT_SKILLS = "about_skills";
    private static final String ABOUT_SOCIAL_LINKS = "about_social_links";
    private static final String BACKGROUND_IMAGE = "background_image";

    /**
     * 显示关于我页面
     */
    @GetMapping("/about")
    public String showAboutPage(Model model) {
        // 添加分类信息
        model.addAttribute("categories", categoryService.getAllCategories());

        // 添加背景图片设置
        String backgroundImage = settingsService.getSettingValueByKey(BACKGROUND_IMAGE, "");
        model.addAttribute("backgroundImage", backgroundImage);

        // 添加关于我的信息
        model.addAttribute("aboutName", settingsService.getSettingValueByKey(ABOUT_NAME, ""));
        model.addAttribute("aboutAvatar", settingsService.getSettingValueByKey(ABOUT_AVATAR, ""));
        model.addAttribute("aboutBio", settingsService.getSettingValueByKey(ABOUT_BIO, ""));

        // 将Markdown内容转换为HTML
        String aboutContent = settingsService.getSettingValueByKey(ABOUT_CONTENT, "");
        if (!aboutContent.isEmpty()) {
            aboutContent = markdownService.convertToHtml(aboutContent);
        }
        model.addAttribute("aboutContent", aboutContent);

        // 处理技能标签
        String skillsStr = settingsService.getSettingValueByKey(ABOUT_SKILLS, "");
        List<String> skills = new ArrayList<>();
        if (!skillsStr.isEmpty()) {
            skills = Arrays.asList(skillsStr.split(","));
        }
        model.addAttribute("aboutSkills", skills);

        // 处理社交链接
        String socialLinksStr = settingsService.getSettingValueByKey(ABOUT_SOCIAL_LINKS, "");
        List<SocialLink> socialLinks = new ArrayList<>();
        if (!socialLinksStr.isEmpty()) {
            try {
                // 格式: name1|url1|icon1,name2|url2|icon2
                String[] links = socialLinksStr.split(",");
                for (String link : links) {
                    String[] parts = link.split("\\|");
                    if (parts.length == 3) {
                        socialLinks.add(new SocialLink(parts[0], parts[1], parts[2]));
                    }
                }
            } catch (Exception e) {
                // 解析错误时使用空列表
            }
        }
        model.addAttribute("socialLinks", socialLinks);

        // 添加当前用户信息和权限
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !auth.getName().equals("anonymousUser")) {
            model.addAttribute("isAdmin", userService.isAdmin(auth.getName()));
            model.addAttribute("currentUser", userService.getUserByUsername(auth.getName()));
        }

        return "about";
    }

    /**
     * 显示关于我设置页面
     */
    @GetMapping("/admin/about")
    @PreAuthorize("hasRole('ADMIN')")
    public String showAboutSettings(Model model) {
        model.addAttribute("aboutName", settingsService.getSettingValueByKey(ABOUT_NAME, ""));
        model.addAttribute("aboutAvatar", settingsService.getSettingValueByKey(ABOUT_AVATAR, ""));
        model.addAttribute("aboutBio", settingsService.getSettingValueByKey(ABOUT_BIO, ""));
        model.addAttribute("aboutContent", settingsService.getSettingValueByKey(ABOUT_CONTENT, ""));
        
        // 技能标签 - 传递原始字符串供前端JavaScript解析
        model.addAttribute("aboutSkills", settingsService.getSettingValueByKey(ABOUT_SKILLS, ""));
        
        // 社交链接 - 传递原始字符串供前端JavaScript解析
        model.addAttribute("aboutSocialLinks", settingsService.getSettingValueByKey(ABOUT_SOCIAL_LINKS, ""));

        return "admin/about-settings";
    }

    /**
     * 保存关于我设置
     */
    @PostMapping("/admin/about")
    @PreAuthorize("hasRole('ADMIN')")
    public String saveAboutSettings(
            @RequestParam("aboutName") String aboutName,
            @RequestParam(value = "avatarFile", required = false) MultipartFile avatarFile, // 接收上传的头像文件
            @RequestParam("aboutAvatar") String aboutAvatar,
            @RequestParam("aboutBio") String aboutBio,
            @RequestParam("aboutContent") String aboutContent,
            @RequestParam("aboutSkills") String aboutSkills,
            @RequestParam("aboutSocialLinks") String aboutSocialLinks,
            RedirectAttributes redirectAttributes) {

        try {
            // --- 新增代码：处理头像上传 ---
            String avatarUrl = aboutAvatar; // 默认使用旧的URL
            if (avatarFile != null && !avatarFile.isEmpty()) {
                // 如果上传了新文件，则调用OssService上传文件并获取返回的URL
                avatarUrl = ossService.uploadFile(avatarFile);
            }
            // --- 新增代码结束 ---

            // 保存所有设置
            settingsService.saveSetting(ABOUT_NAME, aboutName, "关于我 - 名称");
            settingsService.saveSetting(ABOUT_AVATAR, avatarUrl, "关于我 - 头像URL"); // 保存新的头像URL
            settingsService.saveSetting(ABOUT_BIO, aboutBio, "关于我 - 简介");
            settingsService.saveSetting(ABOUT_CONTENT, aboutContent, "关于我 - 详细内容");
            settingsService.saveSetting(ABOUT_SKILLS, aboutSkills, "关于我 - 技能标签");
            settingsService.saveSetting(ABOUT_SOCIAL_LINKS, aboutSocialLinks, "关于我 - 社交链接");

            redirectAttributes.addFlashAttribute("successMessage", "关于我设置已成功保存！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "保存设置时出错：" + e.getMessage());
        }

        return "redirect:/admin/about";
    }
}